package com.wangxu.blog.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wangxu.blog.dao.mapper.ArticleMapper;
import com.wangxu.blog.dao.pojo.Article;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class ThreadService {

    //更新阅读数，期望在线程池中执行不会影响原有的主线程
    @Async("taskExecutor") //调用线程池
    public void updateArticleViewCount(ArticleMapper articleMapper, Article article) {
            int viewCounts = article.getViewCounts();
            Article articleUpdate = new Article();
            articleUpdate.setViewCounts(viewCounts+1);
            LambdaUpdateWrapper<Article> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Article :: getId,article.getId()); //==
            //设置一个，为了在多线程的环境下，线程安全
            //改之前再确认这个值有没有被其他线程抢先修改，类似于CAS操作 cas加自旋，加个循环就是cas
            updateWrapper.eq(Article::getViewCounts,viewCounts);
            //update article set view_count=100 where view_count=99 and id=11
            articleMapper.update(articleUpdate,updateWrapper);
    }
}
